package com.link.base.tencent.corpwx.access.controller;

import com.alibaba.fastjson.JSONObject;
import com.link.base.tencent.corpwx.access.util.ExternalContactEvent;
import com.link.core.cllog.LCLogger;
import com.link.base.tencent.corpwx.access.service.CorpWxAccessService;
import com.link.base.tencent.corpwx.externalcontact.service.ExternalContactService;
import com.link.base.wechat.basic.util.MsgUtil;
import com.link.core.util.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.dom4j.Element;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 企业微信外部用户事件接入
 *
 * @author 欧阳振强
 * @date 2019/1/2
 */
@Controller("externalContactAccessController")
@RequestMapping("/link/corpwx/external_contact")
public class ExternalContactAccessController {
    /**
     * 企业微信相关参数
     */
    private static String corpId = "wwe71019f3bd03b677";
    private static String token = "Ook1FwLPkGOiooEmiaPnp1YXd75YZ4m";
    private static String aesKey = "5U8jo0XotEehfHkyuvD636XJUKACmxoaUvWy2WxCmFc";

    @Resource
    private CorpWxAccessService corpWxAccessService;
    @Resource
    private ExternalContactService externalContactService;

    /**
     * 外部联系人消息事件接入
     *
     * @author 欧阳振强
     * @date 2019/1/2
     */
    @RequestMapping(value = "/access", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public void access(HttpSession session,
                       HttpServletRequest request, HttpServletResponse response) throws Exception {
        String result = "";
        try {
            // 解析xml
            JSONObject jsonObject = corpWxAccessService.parseEventXml(request, corpId, token, aesKey);
            if (StringUtils.isNotBlank(jsonObject.getString("verifyFlag"))) {
                result = jsonObject.getString("verifyFlag");
            } else {
                String resultXml = jsonObject.getString("busFlag");
                Element root = MsgUtil.resolveXml(resultXml);
                // 企业微信CorpID
                String corpId = root.elementText("ToUserName");
                // 成员UserID - 此事件该值固定为sys，表示该消息由系统生成
                String userId = root.elementText("FromUserName");
                // 消息类型
                String msgType = root.elementText("MsgType");
                LCLogger.info().withMessageKey("access").withMessage("企业微信CorpID－>" + corpId + "，成员UserID->" + userId + "，消息类型－>" + msgType).flush();
                if (ExternalContactEvent.EVENT_TYPE.equals(msgType)) {
                    String event = root.elementText("Event");
                    if (ExternalContactEvent.EVENT_TYPE_CHANGE_EXTERNAL_CONTACT.equals(event)) {
                        LCLogger.info().withMessageKey("access").withMessage("外部联系人事件->" + event).flush();
                        String changeType = root.elementText("ChangeType");
                        String corpUserId = root.elementText("UserID");
                        String externalUserID = root.elementText("ExternalUserID");
                        LCLogger.info().withMessageKey("access").withMessage(
                                "changeType -> " + changeType + "，corpUserId -> " + corpUserId + "，externalUserID -> " + externalUserID).flush();
                        if (ExternalContactEvent.EVENT_TYPE_ADD_EXTERNAL_CONTACT.equals(changeType)) {
                            LCLogger.info().withMessageKey("access").withMessage("添加企业客户事件.").flush();
                            // 同步客户信息
                            externalContactService.syncSingleAccountInfoFromWx(externalUserID);
                        } else if (ExternalContactEvent.EVENT_TYPE_ADD_HALF_EXTERNAL_CONTACT.equals(changeType)) {
                            // 外部联系人免密码添加成员
                            // 因为内部成员取消了"加我为联系人时需要验证"开关，故此时客户添加内部成员为好友，但是内部成员尚未添加客户为好友
                            // 待内部成员确认添加客户为好友时，将触发【添加企业客户事件】，因此该事件暂时不做处理
                        } else if (ExternalContactEvent.EVENT_TYPE_DEL_EXTERNAL_CONTACT.equals(changeType)) {
                            LCLogger.info().withMessageKey("access").withMessage("删除企业客户事件.").flush();
                            // 内部成员删除了客户，暂时没理清楚怎么使用
                        } else if (ExternalContactEvent.EVENT_TYPE_DEL_FOLLOW_USER.equals(changeType)) {
                            LCLogger.info().withMessageKey("access").withMessage("删除跟进成员事件.").flush();
                            // 客户删除了内部成员删除，暂时没理清楚怎么使用
                        }
                    }
                }
            }
        } catch (Exception e) {
            LCLogger.withException(e);
        }
        response.getWriter().write(result);
    }
}
